package com.rzjm.api.service.impl;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rzjm.api.dao.ChargerMapper;
import com.rzjm.api.dao.ChargerPortMapper;
import com.rzjm.api.entity.Charger;
import com.rzjm.api.entity.ChargerPort;
import com.rzjm.api.exception.TransactionalException;
import com.rzjm.api.service.ChargerPortService;
import com.rzjm.api.service.ChargerService;
import com.rzjm.api.util.OssUtil;
import com.rzjm.api.util.QRCodeUtilEx;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 充电设备Service业务层处理
 *
 * @author ruoyi
 * @date 2022-05-07
 */
@Service
public class ChargerServiceImpl extends BaseServiceImpl<ChargerMapper, Charger> implements ChargerService {

    @Resource
    private ChargerMapper chargerMapper;
    @Resource
    private ChargerPortMapper chargerPortMapper;
    @Resource
    private ChargerPortService chargerPortService;
    @Resource
    protected RedisTemplate<String, Object> redisTemplate;

    @Value("${web.uploadPath}")
    private String uploadPath;

    @Value("${web.imgPrefix}")
    private String imgPrefix;


    @Override
    @Transactional
    public int initCharger(Charger charger) {
        int num = 0;
        int ret = 0;
        try{
            ret = chargerMapper.insert(charger);
            if(ret <= 0){
                throw new TransactionalException("devicesMapper updateById error");
            }
            for(int i = 0; i < charger.getPointCount(); i++){
                QueryWrapper<ChargerPort> qw = new QueryWrapper<>();
                qw.eq("charger_id",charger.getId());
                qw.eq("port_index",(i + 1));
                qw.last("limit 1");
                ChargerPort chargerPort = chargerPortMapper.selectOne(qw);
                if(chargerPort == null){
                    chargerPort = new ChargerPort();
                    chargerPort.setChargerId(charger.getId());
                    chargerPort.setState(0);
                    chargerPort.setPortIndex(i + 1);
                    chargerPort.setChargerSn(charger.getChargerSn());

                    String port = String.format("%02d",chargerPort.getPortIndex());
                    chargerPort.setChargerNum(chargerPort.getChargerSn() + port);

                    String qrCode = "";
                    String fileName = "device_qr_" + charger.getChargerSn() + port + ".jpg";
                    String content = "https://www.sdyuedou.com/wxmini/charger/qr?sn=" + charger.getChargerSn() + "&port=" + chargerPort.getPortIndex();
                    int upload_type = OssUtil.TYPE_CHARGER;
                    System.out.println("content:  " + content);
                    String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                    QRCodeUtilEx.createQrCodeImg(content, "设备编号：" + chargerPort.getChargerSn() + " "+ port + "端口", null, uploadPath +"/"+img_key, true);
                    qrCode = img_key;
                    chargerPort.setQrCode(qrCode);

                    ret = chargerPortMapper.insert(chargerPort);
                    if(ret <= 0){
                        throw new TransactionalException("devicesEggCellMapper updateById error");
                    }
                }
            }

            try{
                String qrCode = "";
                String fileName = "device_qr_" + charger.getId() + ".jpg";
                String content = "https://www.wanwuyunsheng.com/wxmini/charger/qr?sn=" + charger.getChargerSn() + "&port=1";
                int upload_type = OssUtil.TYPE_CHARGER;
                System.out.println("content:  "+ content);
                String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                QRCodeUtilEx.createQrCodeImg(content, "设备编号：" + charger.getChargerSn(), null, uploadPath + "/" + img_key, true);
                qrCode = img_key;
                charger.setQrCode(qrCode);
            }catch (Exception ex){
                ex.printStackTrace();
            }
            ret = chargerMapper.updateById(charger);
            if(ret <= 0){
                throw new TransactionalException("devicesMapper updateById error");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("productOrderMapper insert error");
        }
        return num;
    }


    @Override
    public Charger getChargerInfoBySn(String charger_sn) {
        QueryWrapper<Charger> qw = new QueryWrapper<>();
        qw.eq("charger_sn",charger_sn);
        qw.last("limit 1");
        Charger charger = null;
        String key = "charger_" + charger_sn;
        boolean blHasKey = redisTemplate.opsForHash().hasKey(key,key);
        if (blHasKey) {
            Object object = redisTemplate.opsForHash().get(key, key);
            String itemDicts = object != null ? object.toString() : "";
            if (StrUtil.isNotEmpty(itemDicts)) {
                JSONObject jsonObject = JSONUtil.parseObj(itemDicts);
                charger = JSONUtil.toBean(JSONUtil.toJsonStr(jsonObject), Charger.class);
            } else {
                charger = chargerMapper.selectOne(qw);
                redisTemplate.opsForHash().put(key, key, JSONUtil.toJsonStr(charger));
            }
        } else {
            charger = chargerMapper.selectOne(qw);
            redisTemplate.opsForHash().put(key, key, JSONUtil.toJsonStr(charger));
        }
        return charger;
    }

    @Override
    public Charger getChargerInfoById(Integer charger_id) {
        Charger charger = null;//chargerMapper.selectById(charger_id);
        String key = "charger_id_" + charger_id;
        boolean blHasKey = redisTemplate.opsForHash().hasKey(key,key);
        if (blHasKey) {
            Object object = redisTemplate.opsForHash().get(key, key);
            String itemDicts = object != null ? object.toString() : "";
            if (StrUtil.isNotEmpty(itemDicts)) {
                JSONObject jsonObject = JSONUtil.parseObj(itemDicts);
                charger = JSONUtil.toBean(JSONUtil.toJsonStr(jsonObject), Charger.class);
            } else {
                charger = chargerMapper.selectById(charger_id);
                redisTemplate.opsForHash().put(key, key, JSONUtil.toJsonStr(charger));
            }
        } else {
            charger = chargerMapper.selectById(charger_id);
            redisTemplate.opsForHash().put(key, key, JSONUtil.toJsonStr(charger));
        }

        if(charger != null){
            if(StrUtil.isNotEmpty(charger.getQrCode())){
                charger.setQrCode(imgPrefix + charger.getQrCode());
            }
        }
        return charger;
    }
}
